package com.hudongwx.godoffood.fragment.FoodMenuFragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.hudongwx.godoffood.R;
import com.hudongwx.godoffood.activity.home_activity.FoodGoodsPageActivity;
import com.hudongwx.godoffood.activity.home_activity.VideoActivity;
import com.hudongwx.godoffood.utils.API.API;
import com.hudongwx.godoffood.utils.MyJsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.HashMap;
import java.util.Map;

@ContentView(R.layout.fragment_fragment5)
public class Fragment5 extends Fragment {
    private String TAG="Fragment3";
    private View view=null;
    JSONArray videoData,goodsData;
    @ViewInject(R.id.frag5_recycler)
    RecyclerView recyclerView;
    Handler handler;
    int p=0;//标记变量，用于记录接收消息状态
    String pageCode=null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (null==view){
            view = x.view().inject(this, inflater, container);
            loadVideoData();

            handler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    int what=msg.what;
                    switch (what){
                        case 1:
                            p++;
                            break;
                    }
                    //如果四条条消息都接收到了，就设置适配器传值
                    if (p==1&&videoData!=null&&goodsData!=null){
                        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(),1);
                        recyclerView.setLayoutManager(gridLayoutManager);
                        recyclerView.setAdapter(new MyRecyclerViewAdapter5(videoData,goodsData));
                    }

                }
            };
        }

        return view;
    }


    //加载食品分类视频数据
    public void loadVideoData(){
        RequestParams params = new RequestParams(API.getFoodMenu());
        x.http().get(params, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                try {
                    JSONArray data = result.getJSONArray("Data");
                    videoData = data;
                    pageCode = videoData.getJSONObject(4).getString("brandcode");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i(TAG, "onError: ");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                loadGoodsData();
            }
        });
    }

    //加载食品分类商品数据
    public void loadGoodsData(){
        RequestParams params = new RequestParams(API.getFoodGoods(pageCode));
        x.http().get(params, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                try {
                    JSONArray data = result.getJSONArray("Data");
                    goodsData = data;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i(TAG, "onError: ");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                //数据加载完成后通过handler发送一条消息
                Message message = handler.obtainMessage();
                message.what=1;
                handler.sendMessage(message);
            }
        });
    }

    class MyRecyclerViewAdapter5 extends RecyclerView.Adapter<MyViewHolder1>{
        JSONArray videoData,goodsData;

        public MyRecyclerViewAdapter5(JSONArray videoData,JSONArray goodsData) {
            this.videoData = videoData;
            this.goodsData = goodsData;
        }

        @Override
        public MyViewHolder1 onCreateViewHolder(ViewGroup parent, int viewType) {
            if (0==viewType){
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.food_video_item, null);
                return new MyViewHolder1(view);
            }else {
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.food_goods_item, null);
                return new MyViewHolder1(view);
            }

        }

        @Override
        public void onBindViewHolder(MyViewHolder1 holder, int position) {
            if (0==position){
                try {
                    JSONObject item = videoData.getJSONObject(4);
                    holder.tv.setText(item.getString("brand"));
                    x.image().bind(holder.iv1,item.getString("BrandIconUrl"));
                    x.image().bind(holder.iv2,item.getString("CoverIconUrl"));

                    //视频播放按钮
                    VideoClickListener5 listener = new VideoClickListener5();
                    //获取视频播放链接和标题
                    Map<String,String> map = new HashMap<>();
                    map.put("title",item.getString("brand"));
                    map.put("videoUrl",item.getString("VideoUrl"));
                    holder.videoStart.setTag(map);
                    holder.videoStart.setOnClickListener(listener);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }else {
                try {
                    //显示到最后一个商品的时候隐藏”下一个“picture_fab
                    if ((position)==goodsData.length()){
                        holder.next.setVisibility(View.INVISIBLE);
                    }
                    JSONObject item = goodsData.getJSONObject(position - 1);
                    if (item.getInt("DPState")==3){
                        holder.saleOut.setVisibility(View.INVISIBLE);
                    }

                    //设置查看详情点击事件
                    GoodsClickListener5 listener = new GoodsClickListener5();
                    JSONArray relevantSpecs = item.getJSONArray("RelevantSpecs");
                    int len = relevantSpecs.length();
                    String[] productIDList = new String[len];//用于存放商品ID
                    for (int i = 0; i < len; i++) {
                        productIDList[i] = relevantSpecs.getJSONObject(i).getString("ProductID");
                    }
                    holder.goodsDetails.setTag(productIDList);
                    holder.goodsDetails.setOnClickListener(listener);

                    //商品图片
                    x.image().bind(holder.goodsIv,item.getJSONArray("CustProductPhotos").getJSONObject(0).getString("url"));
                    holder.goodsTitle.setText(item.getString("ProductName"));
                    holder.goodsContent.setText(item.getString("ZMShortDescribes"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }

        @Override
        public int getItemCount() {
            return goodsData.length()+1;
        }

        @Override
        public int getItemViewType(int position) {
            return position;
        }
    }

    class MyViewHolder1 extends RecyclerView.ViewHolder {
        private TextView tv,goodsTitle,goodsContent,videoStart,goodsDetails;
        private ImageView iv1,iv2,goodsIv,next,saleOut;


        public MyViewHolder1(View itemView) {
            super(itemView);
            this.tv = (TextView) itemView.findViewById(R.id.video_item_title);
            this.iv1 = (ImageView) itemView.findViewById(R.id.video_item_small_img);
            this.iv2 = (ImageView) itemView.findViewById(R.id.video_item_big_img);
            this.videoStart = (TextView) itemView.findViewById(R.id.video_introduce);

            this.goodsIv = (ImageView) itemView.findViewById(R.id.goods_title_img);
            this.next = (ImageView) itemView.findViewById(R.id.goods_next);
            this.saleOut = (ImageView) itemView.findViewById(R.id.goods_sale_out);
            this.goodsTitle = (TextView) itemView.findViewById(R.id.goods_title_tv);
            this.goodsContent = (TextView) itemView.findViewById(R.id.goods_content);
            this.goodsDetails = (TextView) itemView.findViewById(R.id.goods_view_details);
        }
    }

    class VideoClickListener5 implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            Log.i(TAG, "onClick: "+v.getTag());

            Intent intent = new Intent(getActivity(), VideoActivity.class);
            Map<String,String> map = (Map<String, String>) v.getTag();
            String title = map.get("title");
            String url = map.get("videoUrl");
            intent.putExtra("url",url);
            intent.putExtra("title",title);
            startActivity(intent);
        }
    }

    class GoodsClickListener5 implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            Log.i(TAG, "onClick: "+v.getTag());

            Intent intent = new Intent(getActivity(), FoodGoodsPageActivity.class);
            intent.putExtra("productID", (String[]) v.getTag());
            startActivity(intent);

        }
    }
}
